package org.eenie.learn.seedquartz.quartz.manage;


import org.eenie.learn.seedquartz.utils.AppIdGenUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzManager {


    @Autowired
    private Scheduler mScheduler;

    /**
     * 创建定时任务
     */
    public String createTask(Class<? extends Job> job, String desc, String cron) throws SchedulerException {
            String id = genCode();
            JobDetail detail = JobBuilder.newJob(job)
                    .withIdentity(id)
                    .withDescription(desc)
                    .build();
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(cron);

            CronTrigger cronTrigger = TriggerBuilder
                    .newTrigger()

                    .withSchedule(scheduleBuilder)
                    .build();
            mScheduler.scheduleJob(detail, cronTrigger);
            pauseTask(id);
            return id;
    }


    /**
     * 暂停定时任务
     */
    public void pauseTask(String id) {
        try {
            mScheduler.pauseJob(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }    /**
     * 暂停定时任务
     */
    public void pauseTask(JobKey key) {
        try {
            mScheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /**
     * 恢复定时任务
     */
    public void resumeTask(String id) {
        try {
            mScheduler.resumeJob(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取定时任务信息
     */
    public JobDetail fetchTaskInfo(String id) {
        try {
            return mScheduler.getJobDetail(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 移除定时任务
     */
    public void removeTask(String id) {
        try {
            mScheduler.deleteJob(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改定时任务
     */
    public void modifyTask(String id, Class<? extends Job> newJob, String newDesc, String newCron) {
        try {
            mScheduler.getJobDetail(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    private String genCode() {
        return AppIdGenUtils.genAppId();
    }

}
